'''
@author: harumonia
@site:
@datetime: 2020/3/14 20:37
@software: PyCharm
'''
from flask_admin.contrib.sqla import ModelView
from flask_login import UserMixin
from flask_security.utils import hash_password

from application.extensions import db

__all__ = ['Role', 'User']

user_role_table = db.Table('user_role', db.Model.metadata
                           , db.Column('user_id', db.BigInteger, db.ForeignKey('user.id', ondelete='CASCADE'))
                           , db.Column('role_id', db.BigInteger, db.ForeignKey('role.id', ondelete='CASCADE')))


class Permission:
    READ = 0x01
    CREATE = 0x02
    UPDATE = 0x04
    DELETE = 0x08
    DEFAULT = READ


class Role(db.Model):
    __tablename__ = 'role'
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='id')
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))
    permission = db.Column(db.String(20))

    def __repr__(self):
        return "{}-{}".format(self.name, self.permission)

    def __str__(self):
        return self.__repr__()

    def __unicode__(self):
        return self.__repr__()


class User(db.Model, UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='id')
    name = db.Column(db.String(20), comment='用户姓名')
    loginame = db.Column(db.String(20), comment='用户登录名')
    password = db.Column(db.String(255), comment='密码')
    email = db.Column(db.String(255), unique=True, comment='邮箱')
    remark = db.Column(db.String(200), comment='用户说明')

    last_login_at = db.Column(db.DateTime, comment='最后一次登录的时间')
    current_login_at = db.Column(db.DateTime, comment='最近一次登录的时间')
    last_login_ip = db.Column(db.String(20), comment='最后一次登录的ip')
    current_login_ip = db.Column(db.String(20))
    login_count = db.Column(db.Integer, comment='登录次数')

    active = db.Column(db.Boolean(), comment='状态码')
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role',
                            secondary=user_role_table,
                            backref=db.backref('users', lazy='dynamic'),
                            lazy="dynamic")

    # roles = db.relationship('Role', secondary='roles_users',
    #                         backref=db.backref('users', lazy='dynamic'))

    def to_json(self):
        return {"name": self.name,
                "email": self.email,
                "role": self.role.name}

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)

    # Custom User Payload
    def get_security_payload(self):
        return {
            'id': self.id,
            'name': self.name,
            'email': self.email
        }

    def __repr__(self):
        return self.loginame


class UserView(ModelView):
    can_delete = False
    page_size = 50
    can_view_details = False
    column_searchable_list = ['name', 'email']
    column_exclude_list = ['password']
    column_filters = ['login_count']
    column_editable_list = ['name']
    # form_choices = {
    #     'name': [
    #         ('MR', 'Mr'),
    #         ('MRS', 'Mrs'),
    #         ('MS', 'Ms'),
    #         ('DR', 'Dr'),
    #         ('PROF', 'Prof.')
    #     ]
    # }
    form_excluded_columns = ['last_login_at', 'last_login_ip', 'current_login_at', 'current_login_ip', 'login_count']

    def on_model_change(self, form, User, is_created):
        User.password = hash_password(form.password.data)
